<template>
  <div v-if="showAlert" class="browser-alert">
    <div class="browser-alert-content">
      <p>{{ message }}</p>
      <div class="browser-links">
        <a
          v-for="link in browserLinks"
          :key="link.name"
          :href="link.url"
          target="_blank"
          class="browser-link"
        >
          下载 {{ link.name }}
        </a>
      </div>
    </div>
    <button class="close-button" @click="closeAlert">×</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { UAParser } from "ua-parser-js";

const showAlert = ref(false);
const message = ref("");

const browserLinks = [
  {
    name: "Chrome",
    url: "https://www.google.com/chrome/",
  },
  {
    name: "Firefox",
    url: "https://www.mozilla.org/firefox/",
  },
  {
    name: "Edge",
    url: "https://www.microsoft.com/edge",
  },
];

onMounted(() => {
  //   const hasShown = localStorage.getItem("browser-alert-shown");
  //   if (hasShown) return;

  const parser = new UAParser();
  const result = parser.getResult();

  // 检查浏览器版本
  const browser = result.browser;

  if (needsUpgrade(browser)) {
    message.value = `您当前使用的是 ${browser.name} ${browser.version} 版本，
        为了更好的使用体验，建议升级到最新版本。`;
    showAlert.value = true;
  }
});

const closeAlert = () => {
  //   showAlert.value = false;
  localStorage.setItem("browser-alert-shown", "true");
};

const needsUpgrade = (browser) => {
  // 在这里定义版本检查逻辑
  const minVersions = {
    Chrome: 88,
    Firefox: 78,
    Safari: 14,
    "Microsoft Edge": 88,
    IE: Infinity,
  };

  const browserName = browser.name;
  const browserVersion = parseInt(browser.version);
  // console.log(browserVersion);
  return (
    browserName && minVersions[browserName] && browserVersion < minVersions[browserName]
  );
};
</script>

<style scoped>
.browser-alert {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff3cd;
  color: #856404;
  padding: 12px 40px 12px 12px;
  text-align: center;
  z-index: 9999;
  border: 1px solid #ffeeba;
}

.browser-alert-content {
  max-width: 800px;
  margin: 0 auto;
}

.browser-links {
  margin-top: 8px;
}

.browser-link {
  display: inline-block;
  margin: 0 10px;
  color: #0066cc;
  text-decoration: none;
}

.browser-link:hover {
  text-decoration: underline;
}

.close-button {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  border: none;
  background: transparent;
  font-size: 20px;
  cursor: pointer;
  color: #856404;
}
</style>
